const Base = require('./base.js');

module.exports = class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async indexAction() {
    const user = await this.model('admin_list').where({id: this.getLoginUserId()}).find();
    const role = await this.model('role').where({id: user.role_type}).find();
    if (think.isEmpty(role.roles)) {
      return this.success([]);
    }
    const model = this.model('menu');
    const data = await model.order(['sort ASC']).where({id: ['IN', role.roles]}).select();
    const newData = data.filter(item => {
      item.children = [];
      return item.parentId === -1;
    });
    for (const item of data) {
      if (item.parentId === -1) {

      } else {
        for (const newItem of newData) {
          if (item.parentId === newItem.id) {
            newItem.children.push(item);
          }
        }
      }
    }
    return this.success(newData);
  }

  async treeAction() {
    const model = this.model('menu');
    const data = await model.order(['sort ASC']).select();
    const newData = data.filter(item => {
      item.children = [];
      return item.parentId === -1;
    });
    for (const item of data) {
      if (item.parentId === -1) {

      } else {
        for (const newItem of newData) {
          if (item.parentId === newItem.id) {
            newItem.children.push(item);
          }
        }
      }
    }
    return this.success(newData);
  }

  async singleAction() {
    const id = this.get('id');
    const data = await this.model('menu').where({id: id}).find();
    return this.success(data);
  }

  async putAction() {
    const values = this.post();
    const id = this.post('id');
    const model = this.model('menu');

    values.label = values.name;

    if (id > 0) {
      await model.where({id: id}).update(values);
    } else {
      delete values.id;
      await model.add(values);
    }
    return this.success(values);
  }

  async deleteAction() {
    const id = this.get('id');
    await this.model('menu').where({id: id}).limit(1).delete();

    return this.success();
  }
};
